package de.lulusoft.anothertorrent.gui.views.Providers;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;

import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;

import de.lulusoft.anothertorrent.core.rtorrent.Tracker;
import de.lulusoft.anothertorrent.core.rtorrent.TrackerArrayList;

public class TrackerTableContentProvider implements PropertyChangeListener,
		IStructuredContentProvider {

	private TableViewer viewer;

	@SuppressWarnings("unchecked")
	@Override
	public void propertyChange(PropertyChangeEvent evt) {
		ArrayList<Tracker> changedTrackers = (ArrayList<Tracker>)evt.getNewValue();
		if (evt.getPropertyName().equals(TrackerArrayList.PROP_UPDATED))
		{
			viewer.update(changedTrackers.toArray(), null);
		}
	}

	@Override
	public Object[] getElements(Object inputElement) {
		if (inputElement instanceof TrackerArrayList)
		{
			return ((TrackerArrayList)inputElement).toArray();
		}
		return null;
	}

	@Override
	public void dispose() {
		if (viewer.getInput() instanceof TrackerArrayList)
		{
			TrackerArrayList trackers = (TrackerArrayList)viewer.getInput();
			trackers.removeListener(this);
		}
	}

	@Override
	public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
		this.viewer = (TableViewer) viewer;
		if (oldInput instanceof TrackerArrayList)
		{
			TrackerArrayList trackers = (TrackerArrayList)oldInput;
			trackers.removeListener(this);
		}
		if (newInput instanceof TrackerArrayList)
		{
			TrackerArrayList trackers = (TrackerArrayList)newInput;
			trackers.addListener(this);
		}
		viewer.refresh();
	}

}
